/**
 * @file gui_task.cpp
 * @author ThomasKingFree (dulu150@126.com)
 * @brief
 * @version 0.1
 * @date 2021-03-14
 *
 * @copyright Copyright (c) 2021
 *
 */

#include "gui_task.h"

#include <iostream>

namespace YueGUI {
namespace Simulator {
GUIMonitor *GUIMonitor::monitor_ = nullptr;

GUIMonitor::GUIMonitor()
    : window_(nullptr), renderer_(nullptr), texture_(nullptr),
      framebuffer_(nullptr), refresh_(false) {}

GUIMonitor::~GUIMonitor() {
    SDL_DestroyTexture(texture_);
    SDL_DestroyRenderer(renderer_);
    SDL_DestroyWindow(window_);
}

void GUIMonitor::Init() {
    SDL_Init(SDL_INIT_VIDEO);

    window_ = SDL_CreateWindow("YueGUI", SDL_WINDOWPOS_UNDEFINED,
                               SDL_WINDOWPOS_UNDEFINED, SIMULATOR_WIDTH,
                               SIMULATOR_HEIGHT, 0);

    renderer_ = SDL_CreateRenderer(window_, -1, SDL_RENDERER_SOFTWARE);

    texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_ARGB8888,
                                 SDL_TEXTUREACCESS_STATIC, SIMULATOR_WIDTH,
                                 SIMULATOR_HEIGHT);
    SDL_SetTextureBlendMode(texture_, SDL_BLENDMODE_BLEND);

    framebuffer_ = new uint32_t[SIMULATOR_WIDTH * SIMULATOR_HEIGHT];
    memset(framebuffer_, 0xff,
           SIMULATOR_WIDTH * SIMULATOR_HEIGHT * sizeof(uint32_t));
    refresh_ = true;
    monitor_ = this;

    SDL_CreateThread(GUIMonitor::TaskEntry, "sdl", nullptr);
}

void GUIMonitor::Render() { refresh_ = true; }

int GUIMonitor::TaskEntry(void *param) {
    while (true) {
        if (monitor_ == nullptr) {
            continue;
        }

        if (monitor_->refresh_ == false) {
            continue;
        }

        monitor_->refresh_ = false;
        SDL_UpdateTexture(monitor_->texture_, nullptr, monitor_->framebuffer_,
                          SIMULATOR_WIDTH * sizeof(uint32_t));
        SDL_RenderClear(monitor_->renderer_);
        SDL_RenderCopy(monitor_->renderer_, monitor_->texture_, nullptr,
                       nullptr);
        SDL_RenderPresent(monitor_->renderer_);
    }
    return 0;
}
} // namespace Simulator
} // namespace YueGUI
